package com.wrial.simple;
/*
 * @Author  Wrial
 * @Date Created in 15:48 2020/3/29
 * @Description
 * 输入:
	Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7
合并后的树:
	     3
	    / \
	   4   5
	  / \   \
	 5   4   7
 */


public class LeetCode_617 {

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null) return t2;
        if (t2 == null) return t1;
        t1.val += t2.val;
        t1.left = process(t1.left, t2.left);
        t1.right = process(t1.right, t2.right);
        return t1;
    }


    private TreeNode process(TreeNode t1, TreeNode t2) {

        if (t1 == null && t2 == null) return null;
        TreeNode root = new TreeNode((t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val));
        // 此处一定要有三责运算，否则如果此节点为null，就会有空指针异常
        root.left = process(t1==null?null:t1.left, t2==null?null:t2.left);
        root.right = process(t1==null?null:t1.right, t2==null?null:t2.right);
        return root;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

}
